package interpreter.bytecodes;

import interpreter.VirtualMachine;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;
import java.util.Vector;

/**
 *
 * @author Kristofer Selbekk
 */
public class CallByteCode extends ByteCode {

    private String id;
    private int address;
    private Vector<Integer> args;

    /**
     * Initializes the byte code with 1 argument
     */
    public void init( Vector<String> args ) {
        try {
            id = args.get(0);
            this.args = new Vector<Integer>();
        } catch( NumberFormatException nfe ) {
            // If bad format
            System.out.println("Bad format!");
            System.exit(-1);
        } catch( NoSuchElementException nse ) {
            // If empty argument
            System.out.println("Empty vector!");
            System.exit(-1);
        } catch( NullPointerException npe ) {
            // If argument missing
            System.out.println("Argument given = null.");
            System.exit(-1);
        }
    }

    /**
     * Action: Transfers control to the indicated function
     *
     * @param rt the Virtual Machine reference
     */
    public void exec( VirtualMachine rt ) {
        // Gets the program counter
        int pc = rt.getPC();

        // Remember where it was called from in the virtual machine
        rt.addReturnAddress( pc );

        // Saves arguments
        for( int i = rt.getTopFrame(); i < rt.getStackSize(); i++ )
            args.add( rt.getStackElementAt(i) );
        

        // Set new program counter address
        rt.setPC( address );
    }

    public int getAddress() {
        return address;
    }
    public void setAddress( int addr ) {
        address = addr;
    }

    public Object getArgs() {
        return id;
    }

    public String toString() {
        StringTokenizer token;
        String baseID = "";
        if( id != null ) {
            token = new StringTokenizer(id, "<");
            baseID = token.nextToken();
        }

        // Parses the argument list
        String argList = "";
        if( args!=null ) {
            Iterator it = args.iterator();
            
            while( it.hasNext() ) {
                argList += it.next();
                if( it.hasNext() ) argList += ", ";
            }
        }

        return super.toString() + "\t"+ baseID+"("+ argList +")";
    }
}